<template>
  <div>
    <!-- Sidebar -->
    <div class="sidebar">
      <div style="padding: 24px 20px; border-bottom: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; border-radius: 10px; overflow: hidden; flex-shrink: 0;">
            <img src="../../../头像.jpg" alt="头像" style="width: 100%; height: 100%; object-fit: cover;" />
          </div>
          <div style="margin-left: 12px;">
            <div style="font-weight: 600; color: #111827;">快递代拿管理系统</div>
          </div>
        </div>
      </div>

      <div style="padding: 16px 0;">
        <div class="nav-section">主菜单</div>
        <button :class="['nav-item', $route.path === '/admin/dashboard' ? 'active' : '']" @click="$router.push('/admin/dashboard')">
          <i class="fas fa-chart-line"></i>
          <span>数据总览</span>
        </button>
        <button :class="['nav-item', $route.path === '/admin/orders' ? 'active' : '']" @click="$router.push('/admin/orders')">
          <i class="fas fa-box"></i>
          <span>订单管理</span>
        </button>
        <button :class="['nav-item', $route.path === '/admin/users' ? 'active' : '']" @click="$router.push('/admin/users')"><i class="fas fa-users"></i><span>下单者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/couriers' ? 'active' : '']" @click="$router.push('/admin/couriers')"><i class="fas fa-motorcycle"></i><span>代拿者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/finance' ? 'active' : '']" @click="$router.push('/admin/finance')"><i class="fas fa-wallet"></i><span>财务管理</span></button>

        <div class="nav-section">运营管理</div>
        <button :class="['nav-item', $route.path === '/admin/announcements' ? 'active' : '']" @click="$router.push('/admin/announcements')"><i class="fas fa-bullhorn"></i><span>公告管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/pricing' ? 'active' : '']" @click="$router.push('/admin/pricing')"><i class="fas fa-percentage"></i><span>盈利规则</span></button>
        

        <div class="nav-section">系统设置</div>
        <button :class="['nav-item', $route.path === '/admin/permissions' ? 'active' : '']" @click="$router.push('/admin/permissions')"><i class="fas fa-shield-alt"></i><span>权限管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/logs' ? 'active' : '']" @click="$router.push('/admin/logs')"><i class="fas fa-file-alt"></i><span>系统日志</span></button>
        <button :class="['nav-item', $route.path === '/admin/settings' ? 'active' : '']" @click="$router.push('/admin/settings')"><i class="fas fa-cog"></i><span>系统设置</span></button>
      </div>

      <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 20px; border-top: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; border-radius: 50%; background:#e5e7eb; display:flex; align-items:center; justify-content:center; color:#6b7280; font-weight:600;">管</div>
          <div style="margin-left: 12px; flex: 1;">
            <div style="font-weight: 500; color: #111827; font-size: 14px;">管理员</div>
            <div style="font-size: 12px; color: #9ca3af;">超级管理员</div>
          </div>
        </div>
        <button class="nav-item" @click="confirmLogout" style="margin-top:12px;"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></button>
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <!-- Header -->
      <div style="background: white; border-bottom: 1px solid #e5e7eb; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between;">
        <div></div>
        <div style="position: relative;">
          <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #9ca3af;"></i>
          <input v-model="searchKeyword" type="text" placeholder="搜索订单号/用户/地址/状态..." style="padding: 8px 12px 8px 36px; border: 1px solid #e5e7eb; border-radius: 8px; width: 240px; font-size: 14px;">
        </div>
      </div>

      <!-- Content -->
      <div style="padding: 32px;">
        <div style="margin-bottom: 32px;">
          <h1 style="font-size: 28px; font-weight: 700; color: #111827; margin-bottom: 8px;">订单管理</h1>
          <p style="color: #6b7280;">管理所有快递代拿订单</p>
        </div>

        <!-- Filter Card -->
        <div class="filter-card">
          <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px;">
            <div>
              <label style="display: block; margin-bottom: 8px; font-size: 14px; color: #374151; font-weight: 500;">订单状态</label>
              <select v-model="filterStatus" style="width: 100%; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 8px; font-size: 14px;">
                <option value="全部状态">全部状态</option>
                <option value="待接单">待接单</option>
                <option value="配送中">配送中</option>
                <option value="已完成">已完成</option>
                <option value="已取消">已取消</option>
              </select>
            </div>
            <div>
              <label style="display: block; margin-bottom: 8px; font-size: 14px; color: #374151; font-weight: 500;">日期范围</label>
              <div style="display:flex; gap:8px;">
                <input v-model="startDate" type="date" style="flex:1; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 8px; font-size: 14px;" placeholder="yyyy/mm/dd">
                <span style="display:flex; align-items:center; color:#6b7280;">到</span>
                <input v-model="endDate" type="date" style="flex:1; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 8px; font-size: 14px;" placeholder="yyyy/mm/dd">
              </div>
            </div>
            <div>
              <label style="display: block; margin-bottom: 8px; font-size: 14px; color: #374151; font-weight: 500;">代拿员筛选</label>
              <input v-model="courierFilter" placeholder="输入代拿员姓名或手机号" style="width: 100%; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 8px; font-size: 14px;" />
            </div>
            <div style="display: flex; align-items: flex-end; gap: 12px;">
              <button @click="applyFilters" style="flex: 1; padding: 10px 16px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500;">
                <i class="fas fa-search" style="margin-right: 8px;"></i>搜索
              </button>
              <button @click="resetFilters" style="padding: 10px 16px; background: #f3f4f6; color: #374151; border: none; border-radius: 8px; cursor: pointer; font-size: 14px;">
                <i class="fas fa-redo"></i>
              </button>
            </div>
          </div>
        </div>

        <!-- Orders Table -->
        <div class="table-container">
          <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px;">
            <h3 style="font-size: 18px; font-weight: 600; color: #111827;">订单列表</h3>
            <div style="display: flex; gap: 12px;">
              <button @click="exportCsv" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-size: 14px;">
                <i class="fas fa-download"></i>
                <span>导出数据</span>
              </button>
            </div>
          </div>
          <table>
            <thead>
              <tr>
                <th><input type="checkbox"></th>
                <th>订单编号</th>
                <th>用户信息</th>
                <th>代拿员信息</th>
                <th>取件地址</th>
                <th>送达地址</th>
                <th>订单状态</th>
                <th>订单金额</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="o in orders" :key="o.id">
                <td><input type="checkbox"></td>
                <td style="font-weight: 500; color: #3b82f6;">{{ o.id }}</td>
                <td><div>{{ o.orderUserName || '-' }}</div><div style="font-size: 12px; color: #9ca3af;">{{ o.orderUserPhone || '-' }}</div></td>
                <td><div>{{ o.courierName || '-' }}</div><div style="font-size: 12px; color: #9ca3af;">{{ o.courierPhone || '-' }}</div></td>
                <td style="max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ o.pickup_location }}</td>
                <td style="max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ o.delivery_address }}</td>
                <td>
                  <span class="status-badge" :class="statusClass(o.statusText)">{{ o.statusText }}</span>
                </td>
                <td style="font-weight: 600; color: #111827;">¥{{ o.fee }}</td>
                <td style="font-size: 13px; color: #6b7280;">{{ o.created_at }}</td>
                <td>
                  <button @click="openDetail(o.id)" class="action-btn btn-view">查看</button>
                  <button @click="openEdit(o)" class="action-btn btn-edit">编辑</button>
                </td>
              </tr>
            </tbody>
          </table>

          <!-- Pagination -->
          <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 24px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
            <div style="color: #6b7280; font-size: 14px;">显示 {{ pageStart }}-{{ pageEnd }} 条，共 {{ total }} 条记录</div>
            <div style="display: flex; gap: 8px;">
              <button @click="prevPage" :disabled="page<=1" style="padding: 8px 12px; border: 1px solid #e5e7eb; background: white; border-radius: 6px; cursor: pointer; color: #6b7280;">上一页</button>
              <button style="padding: 8px 12px; border: 1px solid #3b82f6; background: #3b82f6; border-radius: 6px; cursor: pointer; color: white;">{{ page }}</button>
              <button @click="nextPage" :disabled="pageEnd>=total" style="padding: 8px 12px; border: 1px solid #e5e7eb; background: white; border-radius: 6px; cursor: pointer; color: #6b7280;">下一页</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 详情弹窗 -->
      <div v-if="showDetail" style="position:fixed; inset:0; background:rgba(0,0,0,.4); display:flex; align-items:center; justify-content:center; z-index:1000;">
        <div style="width: 720px; max-width: 90%; background:#fff; border-radius:12px; padding:24px;">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;">
            <h3 style="font-size:18px; font-weight:600;">订单详情 #{{ detailOrder?.id }}</h3>
            <button @click="showDetail=false" style="border:0; background:transparent; font-size:20px; line-height:1; cursor:pointer;">×</button>
          </div>
          <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px; font-size:14px; color:#374151;">
            <div><strong>下单者：</strong>{{ detailOrder?.order_user_nickname || '-' }}（{{ detailOrder?.order_user_phone || '-' }}）</div>
            <div><strong>代拿员：</strong>{{ detailOrder?.courier_nickname || '-' }}（{{ detailOrder?.courier_phone || '-' }}）</div>
            <div><strong>取件地址：</strong>{{ detailOrder?.pickup_location }}</div>
            <div><strong>送达地址：</strong>{{ detailOrder?.delivery_address }}</div>
            <div><strong>费用建议：</strong>¥{{ detailOrder?.suggested_fee ?? '-' }}</div>
            <div><strong>状态：</strong>{{ detailOrder?.statusText }}</div>
            <div style="grid-column:1/-1;"><strong>备注：</strong>{{ detailOrder?.note || '-' }}</div>
          </div>
        </div>
      </div>

      <!-- 编辑弹窗 -->
      <div v-if="showEdit" style="position:fixed; inset:0; background:rgba(0,0,0,.4); display:flex; align-items:center; justify-content:center; z-index:1000;">
        <div style="width: 720px; max-width: 90%; background:#fff; border-radius:12px; padding:24px;">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;">
            <h3 style="font-size:18px; font-weight:600;">编辑订单 #{{ editForm.id }}</h3>
            <button @click="showEdit=false" style="border:0; background:transparent; font-size:20px; line-height:1; cursor:pointer;">×</button>
          </div>
          <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px;">
            <div>
              <label style="display:block; font-size:12px; color:#6b7280; margin-bottom:6px;">订单状态</label>
              <select v-model="editForm.statusText" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px;">
                <option>待接单</option>
                <option>配送中</option>
                <option>已完成</option>
                <option>已取消</option>
              </select>
            </div>
            <div>
              <label style="display:block; font-size:12px; color:#6b7280; margin-bottom:6px;">代拿员ID</label>
              <input v-model.number="editForm.courier_user" placeholder="输入代拿员用户ID" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px;" />
            </div>
            <div style="grid-column:1/-1;">
              <label style="display:block; font-size:12px; color:#6b7280; margin-bottom:6px;">取件地址</label>
              <input v-model="editForm.pickup_location" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px;" />
            </div>
            <div style="grid-column:1/-1;">
              <label style="display:block; font-size:12px; color:#6b7280; margin-bottom:6px;">送达地址</label>
              <input v-model="editForm.delivery_address" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px;" />
            </div>
            <div>
              <label style="display:block; font-size:12px; color:#6b7280; margin-bottom:6px;">建议费用</label>
              <input v-model.number="editForm.suggested_fee" type="number" step="0.01" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px;" />
            </div>
            <div style="grid-column:1/-1;">
              <label style="display:block; font-size:12px; color:#6b7280; margin-bottom:6px;">备注</label>
              <textarea v-model="editForm.note" rows="3" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px;"></textarea>
            </div>
          </div>
          <div style="display:flex; justify-content:flex-end; gap:12px; margin-top:16px;">
            <button @click="saveEdit" style="padding: 10px 16px; background:#3b82f6; color:#fff; border:0; border-radius:8px; cursor:pointer;">保存</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'AdminOrders',
  data() {
    return {
      searchKeyword: '',
      filterStatus: '全部状态',
      startDate: '',
      endDate: '',
      courierFilter: '',
      startDate: '',
      endDate: '',
      courierFilter: '',
      orders: [],
      page: 1,
      pageSize: 10,
      total: 0,
      // 详情/编辑/创建弹窗
      showDetail: false,
      detailOrder: null,
      showEdit: false,
      editForm: {}
    }
  },
  computed: {},
  mounted() {
    // 进入页面默认加载全部订单
    this.fetchOrders()
  },
  computed: {
    pageStart() {
      if (!this.total) return 0
      return (this.page - 1) * this.pageSize + 1
    },
    pageEnd() {
      return Math.min(this.page * this.pageSize, this.total)
    }
  },
  methods: {
    async fetchOrders() {
      try {
        const params = {
          status: this.filterStatus !== '全部状态' ? this.filterStatus : undefined,
          startDate: this.startDate ? this.startDate.replace(/-/g, '/') : undefined,
          endDate: this.endDate ? this.endDate.replace(/-/g, '/') : undefined,
          courier: this.courierFilter || undefined,
          keyword: this.searchKeyword || undefined,
          page: this.page,
          pageSize: this.pageSize
        }
        const { data } = await axios.get('/api/orders', { params })
        if (data && data.success !== false) {
          this.orders = (data.data || data).map(r => ({
            id: r.id,
            orderUserName: r.order_user_nickname,
            orderUserPhone: r.order_user_phone,
            courierName: r.courier_nickname,
            courierPhone: r.courier_phone,
            pickup_location: r.pickup_location,
            delivery_address: r.delivery_address,
            statusText: this.statusToText(r.status),
            fee: r.final_fee ?? r.suggested_fee ?? 0,
            created_at: r.created_at?.replace('T', ' ').slice(0, 19) || r.created_at
          }))
          this.total = data.total ?? 0
        }
      } catch (e) {
        console.error('获取订单失败', e)
        alert('获取订单失败，请稍后再试')
      }
    },
    prevPage() {
      if (this.page > 1) { this.page -= 1; this.fetchOrders() }
    },
    nextPage() {
      if (this.page * this.pageSize < this.total) { this.page += 1; this.fetchOrders() }
    },
    applyFilters() {
      this.fetchOrders()
    },
    resetFilters() {
      this.filterStatus = '全部状态'
      this.startDate = ''
      this.endDate = ''
      this.courierFilter = ''
      this.searchKeyword = ''
      this.fetchOrders()
    },
    statusClass(status) {
      if (status === '待接单') return 'status-pending'
      if (status === '配送中') return 'status-processing'
      if (status === '已完成') return 'status-completed'
      if (status === '已取消') return 'status-cancelled'
      return ''
    },
    statusToText(code) {
      if (code === 1 || code === '1') return '待接单'
      if (code === 2 || code === '2') return '配送中'
      if (code === 3 || code === '3') return '已完成'
      if (code === 4 || code === '4') return '已取消'
      return code || '-'
    },
    async openDetail(id) {
      try {
        const { data } = await axios.get(`/api/orders/${id}`)
        if (data && data.success !== false) {
          const d = data.data
          d.statusText = this.statusToText(d.status)
          this.detailOrder = d
          this.showDetail = true
        }
      } catch (e) {
        console.error('获取订单详情失败', e)
        alert('获取订单详情失败')
      }
    },
    openEdit(row) {
      this.editForm = {
        id: row.id,
        statusText: row.statusText,
        courier_user: row.courier_user || '',
        pickup_location: row.pickup_location,
        delivery_address: row.delivery_address,
        suggested_fee: row.fee,
        note: row.note || ''
      }
      this.showEdit = true
    },
    async saveEdit() {
      try {
        const payload = {
          status: this.editForm.statusText,
          courier_user: this.editForm.courier_user || null,
          pickup_location: this.editForm.pickup_location,
          delivery_address: this.editForm.delivery_address,
          suggested_fee: this.editForm.suggested_fee,
          note: this.editForm.note
        }
        await axios.put(`/api/orders/${this.editForm.id}`, payload)
        this.showEdit = false
        this.fetchOrders()
      } catch (e) {
        console.error('保存失败', e)
        alert('保存失败，请稍后再试')
      }
    },
    exportCsv() {
      if (!this.orders.length) {
        alert('无可导出的数据')
        return
      }
      const headers = ['订单ID','下单者','下单者手机号','代拿员','代拿员手机号','取件地址','送达地址','状态','金额','创建时间']
      const rows = this.orders.map(o => [
        o.id,
        o.orderUserName || '-',
        o.orderUserPhone || '-',
        o.courierName || '-',
        o.courierPhone || '-',
        o.pickup_location || '-',
        o.delivery_address || '-',
        o.statusText || '-',
        o.fee ?? '-',
        o.created_at || '-'
      ])
      const csv = [headers, ...rows].map(r => r.map(v => `"${String(v).replace(/"/g,'""')}"`).join(',')).join('\n')
      const blob = new Blob(["\ufeff" + csv], { type: 'text/csv;charset=utf-8;' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `orders_${Date.now()}.csv`
      a.click()
      URL.revokeObjectURL(url)
    },
    confirmLogout() {
      if (confirm('是否确认退出？')) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminInfo')
        localStorage.removeItem('userToken')
        this.$router.push('/login')
      }
    }
  }
}
</script>

<style scoped>
.sidebar {
  position: fixed;
  left: 0;
  top: 0;
  width: 240px;
  height: 100vh;
  background: #fff;
  border-right: 1px solid #e5e7eb;
  overflow-y: auto;
}

.main-content {
  margin-left: 240px;
  min-height: 100vh;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  color: #6b7280;
  text-decoration: none;
  transition: all 0.2s;
  cursor: pointer;
  width: 100%;
  background: transparent;
  border: 0;
  text-align: left;
}

.nav-item:hover { background: #f3f4f6; color: #3b82f6; }
.nav-item.active { background: #eff6ff; color: #3b82f6; font-weight: 500; }
.nav-item i { width: 20px; margin-right: 12px; }

.filter-card { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 24px; }
.table-container { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); overflow-x: auto; }

table { width: 100%; border-collapse: collapse; }
th { text-align: left; padding: 12px; color: #6b7280; font-weight: 500; font-size: 13px; border-bottom: 1px solid #e5e7eb; }
td { padding: 16px 12px; border-bottom: 1px solid #f3f4f6; color: #374151; }

.status-badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 500; }
.status-pending { background: #fef3c7; color: #92400e; }
.status-processing { background: #dbeafe; color: #1e40af; }
.status-completed { background: #d1fae5; color: #065f46; }
.status-cancelled { background: #fee2e2; color: #991b1b; }

.nav-section { padding: 16px 20px 8px; font-size: 12px; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; }

.action-btn { padding: 6px 12px; border: none; border-radius: 6px; cursor: pointer; font-size: 13px; margin-right: 8px; transition: all 0.2s; }
.btn-view { background: #f3f4f6; color: #374151; }
.btn-view:hover { background: #e5e7eb; }
.btn-edit { background: #dbeafe; color: #1e40af; }
.btn-edit:hover { background: #bfdbfe; }
.btn-delete { background: #fee2e2; color: #991b1b; }
.btn-delete:hover { background: #fecaca; }
</style>
